<template>
  <div id="table" style="width:50vw">
    <el-table :data="currentPageData" stripe border>

      <el-table-column v-for="item in tHead" :label="item.label" sortable :prop="item.prop" :key="item.index"></el-table-column>

      <slot name="table-operating">
<!--        props的defaultOperating控制是否显示默认的操作列-->
<!--        同时也可以使用具名插槽自定义-->
        <el-table-column label="操作" v-if="defaultOperating">
          <template slot-scope="scope">
            <el-button @click="$emit('rowDelete', scope.$index + (currentPage - 1) * pageSize)" type="text" size="small" style="font-size: 20px" ><i class="el-icon-delete"></i></el-button>
            <el-button @click="$emit('rowUpdate', scope.$index + (currentPage - 1) * pageSize)" type="text" size="small" style="font-size: 20px" ><i class="el-icon-edit"></i></el-button>
          </template>
        </el-table-column>
      </slot>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="this.pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tBody.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Table",
    data() {
      return {
        currentPage: 1,
        pageSize: null
      }
    },
    watch: {
      // element-ui 删除当前页所有row时不会自动翻到上一页
      // 加个监听
      tBody: {
        handler() {
          if (this.tBody.length <= this.pageSize * (this.currentPage - 1) && 1 !== this.currentPage) {
            this.currentPage -= 1
          }
        }
      }
    },
    methods: {
      handleCurrentChange(val) {
        this.currentPage = val
      },
      handleSizeChange(val) {
        this.pageSize = val
      },
    },
    props: {
      // 表格每一列标题
      tHead: {
        type: Array
      },
      // 表格内容
      tBody: {
        type: Array
      },
      // 分页
      pageSizes: {
        type: Array,
        default() {
          return [5, 10, 15, 20]
        }
      },
      defaultOperating: {
        type: Boolean,
        default() {
          return true
        }
      }
    },
    computed: {
      currentPageData() {
        return this.tBody.slice(this.pageSize * (this.currentPage - 1), this.pageSize * this.currentPage)
      }
    },
    created() {
      this.pageSize = this.pageSizes[1]
    }
  }
</script>

<style scoped>

</style>
